package com.group02.community.config;





import com.group02.community.entity.vo.UserTokenVO;
import com.group02.community.utils.JwtUtil;
import com.group02.community.utils.ResponseResult;
import com.group02.community.utils.RsaUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        User user = (User) authentication.getPrincipal();
        String token = JwtUtil.generateToken(user.getUsername(), RsaUtil.privateKey, JwtUtil.EXPIRE_MINUTES);
        UserTokenVO userVO=new UserTokenVO(user.getUsername(),token);
        ResponseResult.write(httpServletResponse,ResponseResult.ok(userVO));
        log.info("user:"+user.getUsername()+",token:"+token);
    }
}
